package commands

import (
	"context"
	"fmt"

	"github.com/spf13/cobra"
)

// NewNetworkCommand 创建网络管理命令
func NewNetworkCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "network",
		Short: "网络管理",
		Long:  "管理虚拟网络",
	}

	cmd.AddCommand(newNetworkListCommand())
	cmd.AddCommand(newNetworkGetCommand())
	cmd.AddCommand(newNetworkCreateCommand())
	cmd.AddCommand(newNetworkDeleteCommand())
	cmd.AddCommand(newNetworkStartCommand())
	cmd.AddCommand(newNetworkStopCommand())
	cmd.AddCommand(newNetworkXMLCommand())

	return cmd
}

func newNetworkListCommand() *cobra.Command {
	var (
		outputFormat string
		connectionID string
	)

	cmd := &cobra.Command{
		Use:   "list",
		Short: "列出所有网络",
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			networks, err := client.Network().ListNetworks(context.Background(), connectionID)
			if err != nil {
				return fmt.Errorf("列出网络失败: %w", err)
			}

			return printOutput(networks, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}

func newNetworkGetCommand() *cobra.Command {
	var (
		outputFormat string
		connectionID string
	)

	cmd := &cobra.Command{
		Use:   "get [name]",
		Short: "获取网络详情",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			network, err := client.Network().GetNetwork(context.Background(), connectionID, args[0])
			if err != nil {
				return fmt.Errorf("获取网络详情失败: %w", err)
			}

			return printOutput(network, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}

func newNetworkCreateCommand() *cobra.Command {
	var (
		connectionID string
		xmlConfig    string
	)

	cmd := &cobra.Command{
		Use:   "create [name]",
		Short: "创建新网络",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())

			err := client.Network().CreateNetwork(context.Background(), connectionID, xmlConfig)
			if err != nil {
				return fmt.Errorf("创建网络失败: %w", err)
			}

			fmt.Printf("✅ 网络 %s 创建成功\n", args[0])
			return nil
		},
	}

	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	cmd.Flags().StringVar(&xmlConfig, "xml", "", "网络 XML 配置")
	return cmd
}

func newNetworkDeleteCommand() *cobra.Command {
	var connectionID string

	cmd := &cobra.Command{
		Use:   "delete [name]",
		Short: "删除网络",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Network().DeleteNetwork(context.Background(), connectionID, args[0])
			if err != nil {
				return fmt.Errorf("删除网络失败: %w", err)
			}

			fmt.Printf("✅ 网络 %s 删除成功\n", args[0])
			return nil
		},
	}

	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}

func newNetworkStartCommand() *cobra.Command {
	var connectionID string

	cmd := &cobra.Command{
		Use:   "start [name]",
		Short: "启动网络",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Network().StartNetwork(context.Background(), connectionID, args[0])
			if err != nil {
				return fmt.Errorf("启动网络失败: %w", err)
			}

			fmt.Printf("✅ 网络 %s 启动成功\n", args[0])
			return nil
		},
	}

	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}

func newNetworkStopCommand() *cobra.Command {
	var connectionID string

	cmd := &cobra.Command{
		Use:   "stop [name]",
		Short: "停止网络",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Network().StopNetwork(context.Background(), connectionID, args[0])
			if err != nil {
				return fmt.Errorf("停止网络失败: %w", err)
			}

			fmt.Printf("✅ 网络 %s 停止成功\n", args[0])
			return nil
		},
	}

	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}

func newNetworkXMLCommand() *cobra.Command {
	var connectionID string

	cmd := &cobra.Command{
		Use:   "xml [name]",
		Short: "获取网络 XML 配置",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			xml, err := client.Network().GetNetworkXML(context.Background(), connectionID, args[0])
			if err != nil {
				return fmt.Errorf("获取网络 XML 配置失败: %w", err)
			}

			fmt.Println(xml)
			return nil
		},
	}

	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}
